package com.weidian.mobile.open.controller;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.weidian.mobile.open.Message;
import com.weidian.mobile.open.utils.HttpUtils;

@RestController
@RequestMapping("/im")
public class EasemobController {
	
	@Autowired
	StringRedisTemplate jedisTemplate;
	
	//注册环信id接口
	@RequestMapping(value="/create", method=RequestMethod.POST)
	@ResponseBody
	public Message registerImAccount(HttpServletRequest req, HttpServletResponse resp) throws Exception{
		String username = req.getParameter("username");
		String passwd = req.getParameter("password");
		String imei = req.getParameter("imei");
		System.err.println(username + "\n" + passwd + "\n" + imei);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("username", username);
		jsonObject.put("password", passwd);
		jsonObject.put("nickname", "" + (System.currentTimeMillis()/1000));
		String ret = HttpUtils.sendPostforEasemob("https://a1.easemob.com/1119161217115396/wonsionton/" + "users", jsonObject.toJSONString(), null);
		System.err.println(ret);
		if (ret.contains("error") && ret.contains("exists")) {
			return Message.error();
		} else if (ret.contains("error")) {
			return Message.error();
		}
		//环信账号存储
		return Message.success();
	}
	
	@RequestMapping(value="/auth", method=RequestMethod.GET)
	@ResponseBody
	public Integer getAuth(HttpServletRequest req, HttpServletResponse resp) throws Exception{
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("grant_type", "client_credentials");
		jsonObject.put("client_id", "YXA65gUuAPwoEeeTdatV-TJOvQ");
		jsonObject.put("client_secret", "YXA6eEI63jLr0A6lktRBne8YetxTBUI");
		String ret = HttpUtils.sendPostforEasemob("https://a1.easemob.com/1119161217115396/wonsionton/" + "token", jsonObject.toJSONString(), null);
		jsonObject = JSON.parseObject(ret);
		String token = jsonObject.getString("access_token");
		System.err.println(token);
		jedisTemplate.opsForValue().set("esmobtoken", token);
		if (ret.contains("error")) {
			return -1;
		}
		return 0;
	}
}
